$(function () {
    $("#questionNameDetail").text(
        "<" + getCookie("nameOfQuestionnaire") + ">答卷分析");

    //传回用户名
    var da = {
        "user": getCookie("userName")
    };
    //添加下拉选择问卷
    var selectContent = ''; //下拉选择内容
    jQuery.ajax({
        type: "POST",
        url: httpRequestUrl + "/queryAllQuestionnaireByCreated",
        data: JSON.stringify(da),
        dataType: 'json',
        contentType: "application/json",
        success: function (result) {
            for (var i = 0; i < result.data.length; i++) {
                selectContent += '<option value="' + result.data[i].id + '">' +
                    result.data[i].questionName + '</option>'
            }
            $("#ddlActivitynew").html(selectContent)
            $("#ddlActivitynew option[value='" + getCookie("questionId") + "']").attr(
                "selected", "selected");
            getQuestionnaireCount();
            getAnswerStatistics();
        }
    });
});

//    切换问卷
$("#ddlActivitynew").change(function () {
    var activity = $(this).val();
    var nameQuestion = $(this)[0].selectedOptions[0].innerHTML;
    if (activity) {
        deleteCookie("questionId");
        setCookie("questionId", activity)
        deleteCookie("nameOfQuestionnaire");
        setCookie("nameOfQuestionnaire", nameQuestion)
        $("#questionNameDetail").html("<" +
            getCookie("nameOfQuestionnaire") + ">答卷分析");
        getQuestionnaireCount();
        getAnswerStatistics();
    }
})

//获得答卷统计数据
function getAnswerStatistics() {
    var data = {
        "questionId": getCookie("questionId")
    };
    jQuery.ajax({
        type: "POST",
        url: httpRequestUrl + "/selectRecordAnswerDetail",
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: "application/json",
        success: function (result) {
            if (result.code === "666") {
                getQuestionTitleList(result);
            } else if (result.code === "20001") {
                console.log(result.data)
                getQuestionTitleList("");
            } else if (result.code === "333") {
                layer.msg(result.message, {icon: 2});
                setTimeout(function () {
                    window.location.href = 'login.html';
                }, 1000)
            } else {
                layer.msg(result.message, {icon: 2})
            }
        }
    });
}

//根据问卷id获取问卷题目标题和问题类型
function getQuestionTitleList(answerStatistics) {
    //console.log(answerStatistics);
    //清除数据
    $("#panel-questionTiTle").empty();
    var data = {
        "questionId": getCookie("questionId")
    }
    commonAjaxPost(true, '/queryQuestionnaireQuestionTitle', data,
        function (result) {
            if (result.code === "666") {
                //清除数据
                $("#column_left").empty();
                $("#column_right").empty();
                //处理数据
                var questionAnswerList = null;
                if (answerStatistics !== "") {
                    questionAnswerList = answerStatistics.data;
                }
                console.log(questionAnswerList);
                //console.log(result.data);
                var questionTitleList = result.data.question;
                //将json字符串转换为json对象
                if (questionTitleList !== null) {
                    var questionTitleListJson = JSON.parse(questionTitleList);
                    //每一个题目加入序号属性
                    for (var i = 0; i < questionTitleListJson.length; i++) {
                        questionTitleListJson[i].index = i;
                    }
                    console.log(questionTitleListJson);
                    //遍历题目
                    for (var i = 0; i < questionTitleListJson.length; i++) {
                        var questionType = questionTitleListJson[i].questionType;
                        //重新排列题目序号，如果题目类型为填空，后面的题目序号减一
                        if (questionType === "2") {
                            for (var j = i + 1; j < questionTitleListJson.length; j++) {
                                questionTitleListJson[j].index -= 1;
                            }
                        }
                        if (questionType === "0") {//单选题
                            singleChoice(questionTitleListJson, questionAnswerList, i, questionTitleListJson[i].index);
                        } else if (questionType === "1") {//多选题
                            multipleChoice(questionTitleListJson, questionAnswerList, i, questionTitleListJson[i].index);
                        } else if (questionType === "4") {//量表题
                            scaleChoice(questionTitleListJson, questionAnswerList, i, questionTitleListJson[i].index);
                        } else if (questionType === "3") {//矩阵量表题
                            matrixScaleChoice(questionTitleListJson, questionAnswerList, i, questionTitleListJson[i].index);
                        }
                    }
                }

            }
        });
}

function getQuestionnaireCount() {
    var url = '/queryQuestionnaireCount';
    var data = {
        "questionId": getCookie("questionId")
    };
    commonAjaxPost(true, url, data, function (result) {
        if (result.code === "666") {
            //清空数据
            $("#effectiveAnswer").empty();
            $("#percentAnswer").empty();
            $("#answerTotal").empty();
            var questCountData = result.data;
            console.log(questCountData);
            var dataName = "";
            if (questCountData.dataId === "2") {
                dataName = "在校生";
            } else if (questCountData.dataId === "3") {
                dataName = "毕业生";
            } else if (questCountData.dataId === "4") {
                dataName = "教师";
            } else if (questCountData.dataId === "5") {
                dataName = "用人单位";
            } else {
                dataName = "-";
            }
            $("#effectiveAnswer").text(questCountData.effectiveAnswer);
            $("#percentAnswer").text(questCountData.answerRate);
            $("#answerTotal").text(questCountData.answerTotal);
        } else if (result.code === "333") {
            layer.msg(result.message, {icon: 2});
        } else if (result.code === "20001") {
        } else {
            layer.msg(result.message, {icon: 2})
        }
    })
}

//

//单选题
function singleChoice(questionTitleListJson, questionAnswerList, i, index) {
    //处理数据，获得选项列表questionTitleArrList和计数列表questionTitleArrListCount
    //取得单选题选项名
    var questionTitleArr = questionTitleListJson[i].questionOption;
    //创建数组存储选项名
    var questionTitleArrList = [];
    //遍历数组
    for (var j = 0; j < questionTitleArr.length; j++) {
        questionTitleArrList.push(questionTitleArr[j].optionWord);
    }
    //获取选项个数
    var optionNUM = questionTitleArr.length;
    //创建选项计数数组，长度为选项个数
    var questionTitleArrListCount = new Array(optionNUM);
    //遍历数组，将数组元素赋值为0
    for (var m = 0; m < optionNUM; m++) {
        questionTitleArrListCount[m] = 0;
        //遍历答卷统计数据
        for (var k = 0; k < questionAnswerList.length; k++) {
            var questionAnswerStr = questionAnswerList[k].questionAnswer;
            var questionAnswer = questionAnswerStr.match(
                /\[(.*?)\]/)[1];
            var questionAnswerArr = questionAnswer.split(",");
            //取得第i道题的答案(即为单选题答案)
            var answer = questionAnswerArr[i];
            if (m === parseInt(answer)) {
                questionTitleArrListCount[m] = questionTitleArrListCount[m] + 1;
            }
        }
    }

    //组合为data_pie
    var data_pie = [];
    for (var n = 0; n < optionNUM; n++) {
        var dataItem = {
            value: questionTitleArrListCount[n],
            name: questionTitleArrList[n]
        };
        data_pie.push(dataItem);
    }
    // console.log(data_pie);

    //根据选项数量，设置颜色
    var color_pie = [];
    if (optionNUM === 2) {
        color_pie = [
            "#006cff",
            "#60cda0"
        ];
    } else if (optionNUM === 3) {
        color_pie = [
            "#006cff",
            "#60cda0",
            "#ed8884"
        ];
    } else if (optionNUM === 4) {
        color_pie = [
            "#006cff",
            "#60cda0",
            "#ed8884",
            "#ff9f7f"
        ];
    } else if (optionNUM === 5) {
        color_pie = [
            "#006cff",
            "#60cda0",
            "#ed8884",
            "#ff9f7f",
            "#0096ff"
        ];
    } else if (optionNUM === 1) {
        color_pie = [
            "#006cff"
        ];
    }
    //插入饼状图
    var text = "";
    text = "<div class=\"panel pie1\">\n" +
        "             <h2>" + (i + 1) + "."
        + questionTitleListJson[i].questionTitle + "</h2>\n" +
        "             <div class=\"chart\" id=\"singlePie_" + i + "\"></div>\n" +
        "             <div class=\"panel-footer\"></div>\n" +
        "         </div>";
    if (index % 2 === 0) {
        $("#column_left").append(text);
    } else {
        $("#column_right").append(text);
    }

    // 点位分布统计模块
    (function () {
        // 1. 实例化对象
        var myChart = echarts.init(document.getElementById('singlePie_' + i));
        // 2. 指定配置项和数据
        var option = {
            legend: {
                top: "90%",
                itemWidth: 10,
                itemHeight: 10,
                textStyle: {
                    color: "rgba(255,255,255,.5)",
                    fontSize: "12"
                }
            },
            tooltip: {
                trigger: "item",
                formatter: "{a} <br/>{b} : {c} ({d}%)"
            },
            // 注意颜色写的位置
            color: color_pie,
            series: [
                {
                    name: "点位统计",
                    type: "pie",
                    // 如果radius是百分比则必须加引号
                    radius: ["10%", "70%"],
                    center: ["50%", "42%"],
                    roseType: "radius",
                    data: data_pie,
                    // 修饰饼形图文字相关的样式 label对象
                    label: {
                        fontSize: 10
                    },
                    // 修饰引导线样式
                    labelLine: {
                        // 连接到图形的线长度
                        length: 10,
                        // 连接到文字的线长度
                        length2: 10
                    }
                }
            ]
        };
        // 3. 配置项和数据给我们的实例化对象
        myChart.setOption(option);
        // 4. 当我们浏览器缩放的时候，图表也等比例缩放
        window.addEventListener("resize", function () {
            // 让我们的图表调用 resize这个方法
            myChart.resize();
        });
    })();
}

//多选题条形图
function multipleChoice(questionTitleListJson, questionAnswerList, i, index) {

    //处理数据，获得选项列表questionTitleArrList和计数列表questionTitleArrListCount
    //取得单选题选项名
    var questionTitleArr = questionTitleListJson[i].questionOption;
    //创建数组存储选项名
    var questionTitleArrList = [];
    //遍历数组
    for (var j = 0; j < questionTitleArr.length; j++) {
        questionTitleArrList.push(questionTitleArr[j].optionWord);
    }
    //获取选项个数
    var optionNUM = questionTitleArr.length;
    //创建选项计数数组，长度为选项个数
    var questionTitleArrListCount = new Array(optionNUM);
    //遍历数组，将数组元素赋值为0
    for (var m = 0; m < optionNUM; m++) {
        questionTitleArrListCount[m] = 0;
        if (questionAnswerList === "A") {

        }

        //遍历答卷统计数据
        for (var k = 0; k < questionAnswerList.length; k++) {
            var questionAnswerStr = questionAnswerList[k].questionAnswer;
            var questionAnswer = questionAnswerStr.match(
                /\[(.*?)\]/)[1];
            var questionAnswerArr = questionAnswer.split(",");
            //取得第i道题的答案(即为单选题答案)
            var answer = questionAnswerArr[i];
            //将answer通过&分割成数组
            var answerArr = answer.split("&");
            //遍历数组
            for (var n = 0; n < answerArr.length; n++) {
                //判断选项名是否与答案相等
                if (m === parseInt(answerArr[n])) {
                    //相等则计数加1
                    questionTitleArrListCount[m]++;
                }
            }
        }
    }
    //questionTitleArrListCount数组 改为百分比 除以总答卷数
    var questionTitleArrListCountPercent = [];
    //计算百分比
    for (var q = 0; q < questionTitleArrListCount.length; q++) {
        questionTitleArrListCountPercent[q] = (questionTitleArrListCount[q]
            / questionAnswerList.length * 100).toFixed(2);
    }

    var text = '<div class="panel bar">\n' +
        "             <h2>" + (i + 1) + "."
        + questionTitleListJson[i].questionTitle + "(%)</h2>\n" +
        '             <div class="chart" id="multipleBar_' + i + '"></div>\n' +
        '             <div class="panel-footer"></div>\n' +
        '         </div>';
    if (index % 2 === 0) {
        $("#column_left").append(text);
    } else {
        $("#column_right").append(text);
    }

    // 柱状图multipleBar模块
    (function () {
        // 实例化对象
        var barTest01 = echarts.init(document.getElementById('multipleBar_' + i));
        // 指定配置和数据
        var option = {
            color: ["#2f89cf"],
            tooltip: {
                trigger: "axis",
                axisPointer: {
                    // 坐标轴指示器，坐标轴触发有效
                    type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            grid: {
                left: "0%",
                top: "10px",
                right: "0%",
                bottom: "4%",
                containLabel: true
            },
            xAxis: [
                {
                    type: "category",
                    data: questionTitleArrList,
                    axisTick: {
                        alignWithLabel: true
                    },
                    axisLabel: {
                        textStyle: {
                            color: "rgba(255,255,255,.6)",
                            fontSize: "12"
                        }
                    },
                    axisLine: {
                        show: false
                    }
                }
            ],
            yAxis: [
                //设置柱状图纵坐标标度为整数
                {
                    type: "value",
                    //minInterval: 1,
                    axisLabel: {
                        textStyle: {
                            color: "rgba(255,255,255,.6)",
                            fontSize: "12"
                        },
                    },
                    axisLine: {
                        lineStyle: {
                            color: "rgba(255,255,255,.1)"
                        }
                    },
                    splitLine: {
                        lineStyle: {
                            color: "rgba(255,255,255,.1)"
                        }
                    }
                }
            ],
            series: [
                {
                    name: "选项小计",
                    type: "bar",
                    barWidth: "35%",
                    data: questionTitleArrListCountPercent,
                    itemStyle: {
                        barBorderRadius: 5
                    }
                }
            ]
        };
        // 把配置给实例对象
        barTest01.setOption(option);
        window.addEventListener("resize", function () {
            barTest01.resize();
        });
    })();
}

//scale 量表题
function scaleChoice(questionTitleListJson, questionAnswerList, i, index) {
    //处理数据，获得选项列表questionTitleArrList和计数列表questionTitleArrListCount
    //取得单选题选项名
    var questionTitleArr = questionTitleListJson[i].questionOption;
    //创建数组存储选项名
    var questionTitleArrList = [];
    //遍历数组
    for (var j = 1; j < questionTitleArr.length - 1; j++) {
        //去除第一个和最后一个字符
        questionTitleArrList.push(questionTitleArr[j].optionWord);
    }
    //获取选项个数
    var optionNUM = questionTitleArr.length - 2;
    //创建选项计数数组，长度为选项个数
    var questionTitleArrListCount = new Array(optionNUM);
    //遍历数组，将数组元素赋值为0
    for (var m = 0; m < optionNUM; m++) {
        questionTitleArrListCount[m] = 0;
        //遍历答卷统计数据
        for (var k = 0; k < questionAnswerList.length; k++) {
            var questionAnswerStr = questionAnswerList[k].questionAnswer;
            var questionAnswer = questionAnswerStr.match(
                /\[(.*?)\]/)[1];
            var questionAnswerArr = questionAnswer.split(",");
            //取得第i道题的答案(即为单选题答案)
            var answer = questionAnswerArr[i];
            if ((m + 1) === parseInt(answer)) {
                questionTitleArrListCount[m] = questionTitleArrListCount[m] + 1;
            }
        }
    }

    //组合为data_pie
    var data_pie = [];
    for (var n = 0; n < optionNUM; n++) {
        var dataItem = {
            value: questionTitleArrListCount[n],
            name: questionTitleArrList[n]
        };
        data_pie.push(dataItem);
    }
    //console.log(data_pie);

    //根据选项数量，设置颜色
    var color_pie = [];
    if (optionNUM === 2) {
        color_pie = [
            "#006cff",
            "#60cda0"
        ];
    } else if (optionNUM === 3) {
        color_pie = [
            "#006cff",
            "#60cda0",
            "#ed8884"
        ];
    } else if (optionNUM === 4) {
        color_pie = [
            "#006cff",
            "#60cda0",
            "#ed8884",
            "#ff9f7f"
        ];
    } else if (optionNUM === 5) {
        color_pie = [
            "#006cff",
            "#60cda0",
            "#ed8884",
            "#ff9f7f",
            "#0096ff"
        ];
    } else if (optionNUM === 1) {
        color_pie = [
            "#006cff"
        ];
    }

    //插入饼形图
    var text = '<div class="panel pie"><h2>' + (i + 1) + "."
        + questionTitleListJson[i].questionTitle
        + '</h2><div class="chart" id="pie_' + i
        + '"></div><div class="panel-footer"></div></div>';
    if (index % 2 === 0) {
        $("#column_left").append(text);
    } else {
        $("#column_right").append(text);
    }

    (function () {
        // 基于准备好的dom，初始化echarts实例
        var myChart = echarts.init(document.getElementById("pie_" + i));
        var option = {
            tooltip: {
                trigger: "item",
                formatter: "{a} <br/>{b}: {c} ({d}%)",
                position: function (p) {
                    //其中p为当前鼠标的位置
                    return [p[0] + 10, p[1] - 10];
                }
            },
            legend: {
                top: "90%",
                itemWidth: 10,
                itemHeight: 10,
                data: questionTitleArrList,
                textStyle: {
                    color: "rgba(255,255,255,.5)",
                    fontSize: "12"
                }
            },
            series: [
                {
                    name: "选项小计",
                    type: "pie",
                    center: ["50%", "42%"],
                    radius: ["40%", "60%"],
                    color: color_pie,
                    label: {show: false},
                    labelLine: {show: false},
                    data: data_pie,
                }
            ]
        };
        // 使用刚指定的配置项和数据显示图表。
        myChart.setOption(option);
        window.addEventListener("resize", function () {
            myChart.resize();
        });
    })();
}

//matrixScaleChoice 矩阵量表题 第i题
function matrixScaleChoice(questionTitleListJson, questionAnswerList, i, index) {

    //处理数据，获得选项列表questionTitleArrList和计数列表questionTitleArrListCount
    //取得单选题选项名
    var questionTitleArr = questionTitleListJson[i].questionOption;
    //创建数组存储选项名
    var questionTitleArrList = [];
    //创建数组行题目名
    var questionLineArrList = [];
    //遍历数组
    for (var j = 0; j < questionTitleArr.length; j++) {
        if (questionTitleArr[j].optionWord !== null
            && questionTitleArr[j].optionWord !== "") {
            questionTitleArrList.push(questionTitleArr[j].optionWord);
        }
        if (questionTitleArr[j].lineTitle !== null && questionTitleArr[j].lineTitle
            !== "") {
            questionLineArrList.push(questionTitleArr[j].lineTitle);
        }
    }

    //获取题目个数(竖着的)
    var questionNum = 0;
    //记录选项个数（横着的）
    var optionNum = 0;
    for (var q = 0; q < questionTitleArr.length; q++) {
        var optionWord2 = questionTitleArr[q].optionWord;
        if (optionWord2 !== null && optionWord2 !== '') {
            optionNum++;
        }
        if (questionTitleArr[q].lineTitle !== '' && questionTitleArr[q].lineTitle
            !== null) {
            questionNum++;
        }
    }

    //创建数组存储每个题目的选项数组
    var questionArrTotalList = [];
    //根据题目数量 创造计数数组
    for (var num = 0; num < questionNum; num++) {
        //创建选项计数数组，长度为选项个数
        var questionTitleArrListCount = new Array(optionNum);
        //遍历数组，将数组元素赋值为0
        for (var to = 0; to < optionNum; to++) {
            questionTitleArrListCount[to] = 0;
        }
        //questionTitleArrListCount[m] = 0;
        //遍历答卷统计数据
        for (var k = 0; k < questionAnswerList.length; k++) {
            var questionAnswerStr = questionAnswerList[k].questionAnswer;
            var questionAnswer = questionAnswerStr.match(
                /\[(.*?)\]/)[1];
            var questionAnswerArr = questionAnswer.split(",");
            //取得第i道题的答案(即为矩阵题答案)
            var answer = questionAnswerArr[i];
            //用&分割答案
            var answerArr = answer.split("&");
            //取得第num的答案
            var answerLine = answerArr[num];
            for (var n = 0; n < optionNum; n++) {
                if (n === parseInt(answerLine)) {
                    questionTitleArrListCount[n]++;
                }
            }
        }
        //将数组中的值转换为百分比
        for (var m = 0; m < optionNum; m++) {
            questionTitleArrListCount[m] = (questionTitleArrListCount[m]
                / questionAnswerList.length * 100).toFixed(2);
        }
        questionArrTotalList.push(questionTitleArrListCount);
    }
    //console.log(questionArrTotalList);

    //插入html
    var text = '<div class="panel bar_' + i + '\"><h2>' + (i + 1) + "."
        + questionTitleListJson[i].questionTitle + '(%)';
    for (var number = 0; number < questionNum; number++) {
        text += '<a href="javascript:;">' + questionLineArrList[number] + '</a>';
    }
    text += '</h2><div class="chart"></div><div class="panel-footer"></div></div>';
    //如果i为偶数

    if (index % 2 === 0) {
        $("#column_left").append(text);
    } else {
        $("#column_right").append(text);
    }

    // 柱状图1模块
    (function () {
            // 实例化对象
            var myChart = echarts.init(
                document.querySelector(".bar_" + i + " .chart"));
            // 指定配置和数据
            var option = {
                color: ["#2f89cf"],
                tooltip: {
                    trigger: "axis",
                    axisPointer: {
                        // 坐标轴指示器，坐标轴触发有效
                        type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                grid: {
                    left: "0%",
                    top: "10px",
                    right: "0%",
                    bottom: "4%",
                    containLabel: true
                },
                xAxis: [
                    {
                        type: "category",
                        data: questionTitleArrList,
                        axisTick: {
                            alignWithLabel: true
                        },
                        axisLabel: {
                            textStyle: {
                                color: "rgba(255,255,255,.6)",
                                fontSize: "12"
                            }
                        },
                        axisLine: {
                            show: false
                        }
                    }
                ],
                yAxis: [
                    {
                        type: "value",
                        axisLabel: {
                            textStyle: {
                                color: "rgba(255,255,255,.6)",
                                fontSize: "12"
                            }
                        },
                        axisLine: {
                            lineStyle: {
                                color: "rgba(255,255,255,.1)"
                                // width: 1,
                                // type: "solid"
                            }
                        },
                        splitLine: {
                            lineStyle: {
                                color: "rgba(255,255,255,.1)"
                            }
                        }
                    }
                ],
                series: [
                    {
                        name: "选项统计",
                        type: "bar",
                        barWidth: "35%",
                        data: questionArrTotalList[0],
                        itemStyle: {
                            barBorderRadius: 5
                        }
                    }
                ]
            };

            // 把配置给实例对象
            myChart.setOption(option);
            window.addEventListener("resize", function () {
                myChart.resize();
            });

            //构造数据变化
            var dataArr = [];
            for (var m = 0; m < questionNum; m++) {
                dataArr.push({
                    year: questionLineArrList[m],
                    data: questionArrTotalList[m]
                });
            }

            $(".bar_" + i + " h2").on("click", "a", function () {
                option.series[0].data = dataArr[$(this).index()].data;
                myChart.setOption(option);
            });
        }
    )
    ();

}


